<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :search.sync="search"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
    >
      <!--      @on-load="onLoad"-->

      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menuLeft">
        <el-button type="warning" size="small" icon="el-icon-download" v-if="permission.manhourQuery_export" @click="handleExport">导出 </el-button>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button icon="el-icon-view" size="small" type="text" v-if="permission.manhourQuery_view" @click="viewDetail(row)">详情 </el-button>
      </template>
      <template slot-scope="" slot="workOrderNoSearch">
        <el-input placeholder="请输入 工单号" v-model="search.workOrderNo">
          <el-button slot="append" icon="el-icon-search" @click="openWorkOrderNoCommonModal"></el-button>
        </el-input>
      </template>
    </avue-crud>
    <el-dialog
      custom-class="manHourQuerydetailDialog"
      v-dragDirectives
      ref="dialog"
      title="详情"
      append-to-body
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      top="7vh"
      @close="showDialog = false"
    >
      <avue-crud
        :option="detail.option"
        :table-loading="detail.loading"
        :data="detail.data"
        :page.sync="detail.page"
        v-model="detail.form"
        ref="detailCrud"
        @current-change="detailCurrentChange"
        @size-change="detailSizeChange"
      >
      </avue-crud>
    </el-dialog>
    <!--    <el-dialog-->
    <!--      v-dragDirectives-->
    <!--      custom-class="manHourQuerydetailDialog"-->
    <!--      ref="dialog"-->
    <!--      title="详情"-->
    <!--      append-to-body-->
    <!--      :visible.sync="mergerWorker.showDialog"-->
    <!--      :close-on-click-modal="false"-->
    <!--      top="5vh"-->
    <!--      @close="mergerWorker.showDialog = false"-->
    <!--    >-->
    <!--      <p class="config-title"><i class="el-icon-vertical-bar"></i>合并工单详情</p>-->
    <!--      <div class="sail-header-dialog-content">-->
    <!--        <avue-crud-->
    <!--          :option="mergerWorker.mergeWorkOrderOption"-->
    <!--          :table-loading="mergerWorker.loading"-->
    <!--          :data="mergerWorker.data"-->
    <!--          :page.sync="mergerWorker.page"-->
    <!--          v-model="mergerWorker.form"-->
    <!--          ref="detailCrud"-->
    <!--          @current-change="mergerWorkerCurrentChange"-->
    <!--          @size-change="mergerWorkerSizeChange"-->
    <!--        >-->
    <!--          <template slot-scope="{ row }" slot="menu">-->
    <!--            <el-button icon="el-icon-view" size="small" type="text" v-if="permission.mergerWorker_view" @click="viewMergeWorkOrderDetail(row)">详情 </el-button>-->
    <!--          </template>-->
    <!--        </avue-crud>-->
    <!--      </div>-->
    <!--    </el-dialog>-->

    <!--    <el-dialog-->
    <!--      v-dragDirectives-->
    <!--      ref="dialog"-->
    <!--      title="人员信息"-->
    <!--      append-to-body-->
    <!--      :visible.sync="userInfo.showDialog"-->
    <!--      :close-on-click-modal="false"-->
    <!--      top="5vh"-->
    <!--      @close="userInfo.showDialog = false"-->
    <!--    >-->
    <!--      <div class="sail-header-dialog-content">-->
    <!--        <avue-crud :option="userInfo.userInfoOption" :table-loading="userInfo.loading" :data="userInfo.data" v-model="userInfo.form" ref="detailCrud"> </avue-crud>-->
    <!--      </div>-->
    <!--    </el-dialog>-->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    <export-comp ref="exportComp" page-api-url="mes-product/stat-work-hour-summary/page" :option="option" :page="page" :query="exportParams" file-name="工时查询"></export-comp>
  </basic-container>
</template>

<script>
import { getList, getDetail } from '@/api/report/manHourQuery';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import exportComp from '@/components/export-comp';
import moment from 'moment/moment';
// import { mergeWorkOrderOption, userInfoOption } from '@/views/report/manHourQueryOption';
import { filterEmptyValues } from '@/util/util';

export default {
  name: 'ReportScrapRecordQuery',
  components: {
    CommonModalTemplate,
    exportComp
  },
  data() {
    return {
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      form: {},
      query: {},
      loading: false,
      exportParams: {},
      page: {
        pageSize: 15,
        currentPage: 1,
        total: 0
      },
      search: {},
      selectionList: [],
      option: {
        height: 'calc(100vh - 470px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 6,
        searchMenuSpan: 24,
        labelWidth: 100,
        border: true,
        index: true,
        editBtn: false,
        viewBtn: false,
        selection: true,
        delBtn: false,
        addBtn: false,
        dialogClickModal: false,
        indexLabel: '序号',
        searchMenuPosition: 'right',
        columnBtn: false,
        searchLabelWidth: 100,
        menuWidth: 100,
        column: [
          {
            label: '生产订单',
            prop: 'productionOrderNo',
            search: true,
            searchOrder: 3
          },
          {
            label: '工单号',
            prop: 'workOrderNo',
            search: true,
            searchOrder: 4
          },
          {
            label: '产品编码',
            prop: 'productPartNo',
            search: true,
            searchOrder: 5
          },
          {
            label: '产品型号',
            prop: 'productPartModel'
          },
          {
            label: '工单数量',
            prop: 'workOrderPlanQuantity'
          },
          {
            label: '开始时间',
            prop: 'examineDate',
            searchLabelWidth: 120,
            search: true,
            searchOrder: 1,
            searchRequire: true,
            searchType: 'datetimerange',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期',
            formatter: (val) => {
              return val.eventTime;
            },
            searchRules: [
              {
                required: true,
                message: '请选择时间范围',
                trigger: 'blur'
              },
              {
                trigger: 'change',
                validator: (rule, value, callback) => {
                  const endTime = value[1];
                  const startTime = value[0];
                  if (moment(endTime).diff(moment(startTime), 'day') > 90) {
                    callback(new Error('查询时间最多选择90天'));
                  }
                  callback();
                }
              }
            ]
          },
          {
            label: '工段',
            prop: 'sectionName'
          },
          {
            label: '产线',
            prop: 'lineId',
            type: 'select',
            search: true,
            filterable: true,
            searchOrder: 6,
            dicUrl: '/api/mes-product/product/line/page?current=1&size=10000',
            dicFormatter: (data) => {
              return data.data.records || [];
            },
            props: {
              label: 'name',
              value: 'id'
            }
          },
          {
            label: '有效工时',
            prop: 'validWorkHours'
          },
          {
            label: '无效工时',
            prop: 'invalidWorkHours'
          },
          {
            label: '产线总工时',
            prop: 'accumulateLineHours'
          },
          {
            label: '人工总工时',
            prop: 'accumulateLaborHours'
          },
          {
            label: '总产量',
            prop: 'productQuantity'
          }
        ]
      },
      data: [],
      showDialog: false,
      rowInfo: {},
      mergeWorkOrderInfo: {},
      detail: {
        loading: false,
        data: [],
        page: {
          pageSize: 15,
          currentPage: 1,
          total: 0
        },
        form: {},
        option: {
          height: 'calc(100vh - 485px)',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchSpan: 6,
          searchMenuSpan: 18,
          labelWidth: 100,
          border: true,
          index: true,
          editBtn: false,
          viewBtn: false,
          selection: false,
          delBtn: false,
          addBtn: false,
          dialogClickModal: false,
          indexLabel: '序号',
          searchMenuPosition: 'right',
          columnBtn: false,
          refreshBtn: false,
          searchLabelWidth: 100,
          menu: false,
          column: [
            {
              label: '类型',
              prop: 'type',
              type: 'select',
              dicData: [
                {
                  label: '作业时间',
                  value: 1
                },
                {
                  label: '间隔时间',
                  value: 2
                }
              ]
            },
            {
              label: '产线',
              prop: 'lineName'
            },
            {
              label: '班组',
              prop: 'shiftGroupName'
            },
            {
              label: '人数',
              prop: 'shiftGroupTeamSize'
            },
            {
              label: '开始时间',
              prop: 'startTime',
              width: 150
            },
            {
              label: '结束时间',
              prop: 'endTime',
              width: 150
            },
            {
              label: '产线工时',
              prop: 'accumulateLineHour'
            },
            {
              label: '人工工时',
              prop: 'accumulateLaborHours'
            },
            {
              label: '产量',
              prop: 'productQuantity'
            }
          ]
        }
      }
      // mergerWorker: {
      //   data: [],
      //   loading: false,
      //   mergeWorkOrderOption,
      //   page: {
      //     pageSize: 15,
      //     currentPage: 1,
      //     total: 0
      //   },
      //   showDialog: false
      // }
      // userInfo: {
      //   rowInfo: {},
      //   loading: false,
      //   data: [],
      //   form: {},
      //   page: {
      //     pageSize: 15,
      //     currentPage: 1,
      //     total: 0
      //   },
      //   showDialog: false,
      //   userInfoOption
      // }
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  created() {},
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      const queryParams = this._cloneDeep(this.search);
      if (queryParams.examineDate && queryParams.examineDate.length) {
        queryParams.startTime = queryParams.examineDate[0];
        queryParams.endTime = queryParams.examineDate[1];
        delete queryParams.examineDate;
      }
      getList(page.currentPage, page.pageSize, queryParams)
        .then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records || [];
          this.selectionClear();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    viewDetail(row) {
      Object.assign(this.rowInfo, {
        lineId: row.lineId,
        sectionId: row.sectionId,
        workshopId: row.workshopId,
        workOrderNo: row.workOrderNo
      });
      this.getDetailData();
      this.showDialog = true;
    },
    viewMergeWorkOrderDetail(row) {
      Object.assign(this.mergeWorkOrderInfo, {
        lineId: row.lineId,
        partNo: row.partNo,
        sectionId: row.sectionId,
        workOrderId: row.workOrderId
      });
      this.getMergeWorkOrderDetailData();
      this.showDialog = true;
    },
    getMergeWorkOrderDetailData() {
      this.detail.loading = true;
      getDetail(this.detail.page.currentPage, this.detail.page.pageSize, this.mergeWorkOrderInfo)
        .then((res) => {
          const data = res.data.data;
          this.detail.page.total = data.total;
          this.detail.data = data.records || [];
        })
        .finally(() => {
          this.detail.loading = false;
        });
    },
    getDetailData() {
      this.detail.loading = true;
      getDetail(this.detail.page.currentPage, this.detail.page.pageSize, this.rowInfo)
        .then((res) => {
          const data = res.data.data;
          this.detail.page.total = data.total;
          this.detail.data = data.records || [];
        })
        .finally(() => {
          this.detail.loading = false;
        });
    },
    detailCurrentChange(currentPage) {
      this.detail.page.currentPage = currentPage;
      this.getDetailData();
    },
    detailSizeChange(pageSize) {
      this.detail.page.pageSize = pageSize;
      this.getDetailData();
    },
    mergerWorkerCurrentChange(currentPage) {
      this.mergerWorker.page.currentPage = currentPage;
      this.mergerWorkerLoad();
    },
    mergerWorkerSizeChange(pageSize) {
      this.mergerWorker.page.pageSize = pageSize;
      this.mergerWorkerLoad();
    },

    // userInfoCurrentChange(currentPage) {
    //   this.userInfo.page.currentPage = currentPage;
    //   this.userInfoLoad();
    // },
    // userInfoSizeChange(pageSize) {
    //   this.userInfoCurrentChange.page.pageSize = pageSize;
    //   this.userInfoLoad();
    // },
    // userInfoLoad() {
    //   this.userInfo.loading = true;
    //   getUserInfoData(this.userInfo.page.currentPage, this.userInfo.page.pageSize, this.userInfo.rowInfo)
    //     .then((res) => {
    //       const data = res.data.data;
    //       this.userInfo.page.total = data.total;
    //       this.userInfo.data = data.records || [];
    //     })
    //     .finally(() => {
    //       this.userInfo.loading = false;
    //     });
    // },
    // mergerWorkerLoad() {
    //   this.mergerWorker.loading = true;
    //   getMergeWorkerData(this.mergerWorker.page.currentPage, this.mergerWorker.page.pageSize, this.rowInfo.workOrderId)
    //     .then((res) => {
    //       const data = res.data.data;
    //       this.mergerWorker.page.total = data.total;
    //       this.mergerWorker.data = data.records;
    //     })
    //     .finally(() => {
    //       this.mergerWorker.loading = false;
    //     });
    // },
    handleExport() {
      const exportParams = this._cloneDeep(this.search);
      if (exportParams.examineDate && exportParams.examineDate.length) {
        exportParams.startDate = exportParams.examineDate[0];
        exportParams.endDate = exportParams.examineDate[1];
        delete exportParams.examineDate;
      }
      this.exportParams = filterEmptyValues(exportParams);
      this.$refs.exportComp.visible = true;
    },
    async viewTeamSize(row) {
      const { shiftGroupName, startTime = '', endTime = '' } = row;
      this.userInfo.loading = true;
      this.userInfo.showDialog = true;
      try {
        const res = await getUserInfoData({ shiftGroupName, startTime, endTime });
        const jsonData = res.data.data;
        if (jsonData) {
          this.userInfo.data = JSON.parse(jsonData.attendanceListJson) || [];
        }
      } catch (e) {
        this.userInfo.data = [];
        console.log(e);
      } finally {
        this.userInfo.loading = false;
      }
    },
    openWorkOrderNoCommonModal() {
      this.modalName = 'workOrderNoModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择工单号（双击进行选择）',
        url: '/api/mes-product/work-order/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '工单类型',
            prop: 'type',
            span: 8,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=order_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '工单号',
            prop: 'workOrderNo',
            searchOrder: 1,
            width: 150,
            overHidden: true,
            search: true
          },
          {
            label: '生产订单',
            prop: 'productionOrderNo',
            search: true,
            width: 120,
            searchOrder: 2,
            searchType: 'input',
            overHidden: true,
            type: 'search'
          },
          {
            label: '产品编码',
            prop: 'productPartNo',
            search: true,
            searchOrder: 3,
            searchType: 'input',
            type: 'search',
            overHidden: true,
            dicData: []
          },
          {
            label: '产品名称',
            prop: 'productPartName',
            search: true,
            overHidden: true,
            searchOrder: 4
          },
          {
            label: '产品型号',
            overHidden: true,
            prop: 'productPartModel',
            searchOrder: 5
          },
          {
            label: 'BOM版本',
            prop: 'bomVersion',
            width: 100
          },
          {
            label: '工单计划数量',
            prop: 'planQuantity',
            width: 100
          },
          {
            label: '计划开始时间',
            prop: 'planStartTime'
          },
          {
            label: '计划结束时间',
            prop: 'planEndTime'
          },
          {
            label: '工单状态',
            prop: 'status',
            searchOrder: 7,
            type: 'select',
            search: true,
            width: 80,
            addDisplay: false,
            editDisplay: false,
            html: true,
            formatter: (val) => this.$statusText.GD(val.status),
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=mfg_work_order'
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    },
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'workOrderNoModal':
          this.search.workOrderNo = this._get(rowData, 'workOrderNo', '');
          break;
        default:
          break;
      }
    }
  }
};
</script>

<style lang="scss">
.manHourQuerydetailDialog {
  .avue-crud__menu {
    display: none;
  }

  .config-title {
    font-size: 16px;
    font-weight: bold;
  }
}
</style>
